/**
 * 鏂囦欢鍚嶏細WidgetController.java
 *
 * 鐗堟湰淇℃伅锛歷1.0
 * 鏃ユ湡锛�013-6-22
 * Copyright  Corporation 2013 
 * 鐗堟潈鎵�湁
 *
 */

package com.foreveross.bsl.mam.model.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.common.utils.bean.FileUtils;
import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;
import com.foreveross.bsl.mam.model.application.AttachmentApplication;
import com.foreveross.bsl.mam.model.application.WidgetApplication;
import com.foreveross.bsl.mam.model.application.WidgetCategoryApplication;
import com.foreveross.bsl.mam.model.application.WidgetVersionApplication;
import com.foreveross.bsl.mam.model.application.vo.AttachmentVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetCategoryVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVersionVO;

/**
 * 模块管理应用层级类
 * 
 * @author: panhm@foreveross.com
 * @version: 2013-6-22 时间：4:49:42
 */

@Controller
@RequestMapping(value = "/mam/widget")
public class WidgetController extends WidgetBaseController {
	private Log log = LogFactory.getLog("WidgetController");

	@Inject
	private WidgetApplication widgetApplication;

	@Inject
	private AttachmentApplication attachmentApplication;

	@Inject
	private WidgetCategoryApplication widgetCategoryApplication;

	@Inject
	private WidgetVersionApplication widgetVersionApplication;

	/**
	 * 验证模块名称
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 
	 */
	@ResponseBody
	@RequestMapping("/checkName")
	public Map<String, String> checkName(@RequestParam("checkName") String name) {

		Map<String, String> result = new HashMap<String, String>();
		WidgetVO res = widgetApplication.checkName(name);
		if (res != null) {
			result.put("result", "true");
		} else {
			result.put("result", "false");
		}
		return result;
	}

	/**
	 * 验证模块标识
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 
	 */
	@ResponseBody
	@RequestMapping("/checkIdentify")
	public Map<String, String> checkIdentify(@RequestParam String identify) {

		Map<String, String> result = new HashMap<String, String>();
		WidgetVO res = widgetApplication.checkIdentity(identify);
		if (res != null) {
			result.put("result", "1");
		} else {
			result.put("result", "0");
		}

		return result;
	}

	/**
	 * 添加模块
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 涓嬪崍4:55:28
	 */

	@RequestMapping("/add")
	public String add(WidgetVO widgetVO, HttpServletRequest request) {
		widgetVO.setAvailable(1);
		Date date = new Date();
		widgetVO.setCreated_at(date);
		widgetVO.setModified_at(date);

		Map<String, Object> jsonConfig = new HashMap<String, Object>();
		jsonConfig.put("name", widgetVO.getName());
		WidgetVersionVO versionVO = widgetVO.getwVersion().get(0);
		jsonConfig.put("version", versionVO.getVersion());
		jsonConfig.put("identifier", widgetVO.getIdentify());
		jsonConfig.put("discription", widgetVO.getDiscription());
		jsonConfig.put("hidden", widgetVO.isHidden());
		jsonConfig.put("isAutoShow", widgetVO.isAutoShow());
		jsonConfig.put("showIntervalTime", widgetVO.getShowIntervalTime());
		jsonConfig.put("timeUnit", widgetVO.getTimeUnit());
		try {
			if (widgetVO.getLocal() == "") {

				AttachmentVO vo = attachmentApplication.getEntity(versionVO
						.getBoundle());
				String filePath = FileUtils.modifyConfigFile(
						vo.getLocalFilename(), jsonConfig);
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				String fileid = fs.saveFile(filePath, null, null);
				vo.setId(fileid);
				vo.setLocalFilename(fileid);
				attachmentApplication.saveEntity(vo);
			}
			widgetApplication.saveEntity(widgetVO);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("[add]", e);
			e.printStackTrace();
		}

		return "redirect:list-view";
	}

	/**
	 * 模块列表
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 
	 */

	@RequestMapping("/list-view")
	public String listView(Model model, String category_id, String name) {
		List<WidgetCategoryVO> listCategory = widgetCategoryApplication
				.findAll();
		List<WidgetCategoryVO> list = new ArrayList<WidgetCategoryVO>();
		if (StringUtils.isNotEmpty(category_id) || StringUtils.isNotEmpty(name)) {
			list = query(category_id, name);
		} else {
			if (listCategory != null) {
				for (int i = 0; i < listCategory.size(); i++) {
					WidgetCategoryVO category = listCategory.get(i);
					List<WidgetVO> listWidgetVO = widgetApplication
							.findByCategoryId(category.getId());
					if (listWidgetVO != null && listWidgetVO.size() > 0) {
						category.setListWidgetVO(listWidgetVO);
						list.add(category);
					}
				}
			}
		}
		model.addAttribute("listCategory", listCategory);
		model.addAttribute("list", list);
		model.addAttribute("name", name);
		model.addAttribute("category_id", category_id);
		return "model/widget-list";
	}

	private List<WidgetCategoryVO> query(String category_id, String name) {
		List<WidgetCategoryVO> list = new ArrayList<WidgetCategoryVO>();
		if (StringUtils.isNotEmpty(category_id)) {// 
			WidgetCategoryVO category = widgetCategoryApplication
					.getEntity(category_id);
			if (StringUtils.isNotEmpty(name)) {//
				List<WidgetVO> listWidgetVO = widgetApplication.findByQuery(
						category_id, name);
				category.setListWidgetVO(listWidgetVO);
			} else {
				List<WidgetVO> listWidgetVO = widgetApplication
						.findByCategoryId(category_id);
				category.setListWidgetVO(listWidgetVO);
			}
			list.add(category);
		} else {
			WidgetCategoryVO category = new WidgetCategoryVO();//
			if (StringUtils.isNotEmpty(name)) {//
				List<WidgetVO> listWidgetVO = widgetApplication.findByQuery(
						category_id, name);
				category.setListWidgetVO(listWidgetVO);
				list.add(category);
			}
		}
		return list;
	}

	/**
	 * 添加页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/add-view")
	public String addView(Model model) {

		List<WidgetCategoryVO> list = widgetCategoryApplication.findAll();
		model.addAttribute("list", list);
		return "model/widget-add";
	}

	/**
	 * 模块详情页
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/widget-view/{id}")
	public String view(Model model, @PathVariable String id) {
		WidgetVO widgetVO = widgetApplication.getEntity(id);
		model.addAttribute("widgetVO", widgetVO);
		List<WidgetVersionVO> listVersion = widgetVersionApplication
				.findByWidgetId(id);
		if (listVersion != null && listVersion.size() > 0) {
			WidgetVersionVO versionVO = listVersion.get(0);
			model.addAttribute("versionVO", versionVO);
		}
		model.addAttribute("listVersion", listVersion);
		WidgetCategoryVO categoryVO = widgetCategoryApplication
				.getEntity(widgetVO.getCategory_id());
		model.addAttribute("categoryVO", categoryVO);

		return "model/widget-view";
	}

	/**
	 * 模块更新页
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/update-view/{id}")
	public String listUpdate(Model model, @PathVariable String id) {
		WidgetVO widgetVO = widgetApplication.getEntity(id);
		WidgetCategoryVO categoryVO = widgetCategoryApplication
				.getEntity(widgetVO.getCategory_id());
		widgetVO.setCategoryVO(categoryVO);
		model.addAttribute("widgetVO", widgetVO);
		List<WidgetCategoryVO> list = widgetCategoryApplication.findAll();
		model.addAttribute("list", list);
		return "model/widget-update";
	}

	/**
	 * 模块更新
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 
	 */

	@RequestMapping("/update")
	@ResponseBody
	public Map<String, String> update(WidgetVO widgetVO) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			widgetApplication.updateEntity(widgetVO.getId(), widgetVO);
			result.put("result", "success");
			result.put("id", widgetVO.getId());
		} catch (Exception e) {
			log.error("[update]", e);
			result.put("result", "error");
		}
		return result;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(String id) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			widgetApplication.deleteEntity(id);
			result.put("result", "success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("[delete]", e);
			result.put("result", "error");
		}
		return result;
	}

	@RequestMapping("/autoShow")
	@ResponseBody
	public Map<String, String> hasAutoShow() {
		Map<String, String> result = new HashMap<String, String>();
		WidgetVO vo = widgetApplication.autoShow();
		if (vo != null) {
			result.put("result", "true");
			result.put("id", vo.getId());
		} else {
			result.put("result", "false");
		}
		return result;
	}

	@RequestMapping("/autoShowSatus")
	@ResponseBody
	public Map<String, String> autoShowSatusUpdate(@RequestParam("id") String id) {
		Map<String, String> result = new HashMap<String, String>();
		widgetApplication.autoShowSatus(id);
		result.put("result", "success");
		return result;
	}

}
